package com.zitangkou.user.security;

import com.google.gson.Gson;
import com.zitangkou.common.enums.RespEnum;
import com.zitangkou.common.global.GlobalResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Deng Ningning
 * @version 1.0
 * @date 2020/8/14 17:32
 */
@Component
@Slf4j
public class TokenAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        // 权限不足
        log.info("权限不足：{}", accessDeniedException.getMessage());
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.print(new Gson().toJson(GlobalResp.fail(RespEnum.NOT_AUTHORIZATION)));
        printWriter.flush();
    }
}
